import Vue from "vue"
import VueRouter from "vue-router"
import Login from "@/components/MyLogin.vue"

// 声明home组件
import Home from "@/components/MyHome.vue"

// 声明home组件中的二级路由对应的组件
import MyGoods from "@/components/menus/MyGoods.vue"
import MyUsers from "@/components/menus/MyUsers.vue"
import MyOrders from "@/components/menus/MyOrders.vue"
import MyRights from "@/components/menus/MyRights.vue"
import MySettings from "@/components/menus/MySettings.vue"

// 声明userdetail组件
import UserDetail from "@/components/user/MyUserDetail.vue"

// 导入需要使用前置守卫判断的路径的数组
import pathArr from "@/router/pathArr.js"

Vue.use(VueRouter)
const router = new VueRouter({
  routes: [
    {path: '/login', component: Login},
    {path: '/', redirect: '/login'},
    {
      path: '/home',
      component: Home,
      redirect:'/home/users',
      children: [
        {path: 'users', component: MyUsers},
        {path: 'goods', component: MyGoods},
        {path: 'orders', component: MyOrders},
        {path: 'rights', component: MyRights},
        {path: 'settings', component: MySettings},
        {path: 'userinfo/:id', component: UserDetail, props:true}
      ]
    }
  ]
})
router.beforeEach(function(to, from, next) {
  // 用to.path === '/home'来判断该地址是否需要守卫
  // 也可以用to.path in pathArr[path1,path2,path3,...]来判断
  if(pathArr.indexOf(to.path) !== -1) {
    if(localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
export default router